<template>
  <div>
    <h1>文件</h1>
    <!-- 显示当前路径 -->
    <p>当前路径: {{ currentPath || '/' }}</p>
    <n-button style="margin: 5px;" @click="goBack" v-if="currentPath">返回上一级</n-button>
    <!-- 按钮：刷新文件列表 -->
    <n-button style="margin: 5px;" @click="fetchFiles">刷新</n-button>
    <!-- 按钮：新建文件夹 -->
    <n-popover trigger="click" placement="bottom-start">
      <template #trigger>
        <n-button style="margin: 5px;">新建文件夹</n-button>
      </template>
      <div>
        <n-input :value="folderName" @update:value="(val) => folderName = val" placeholder="请输入文件夹名：" />
        <n-button @click="addFolder()">确定</n-button>
      </div>
    </n-popover>
    <!-- 文件上传 -->
    <n-upload action="/api/upload" :headers="{}" :data="{}" @finish="handleUploadFinish">
      <n-button style="margin: 5px;">上传文件</n-button>
    </n-upload>
    <ul>
      <li v-for="file in files" :key="file.name">
        <template v-if="file.isDir">
          <!-- 进入文件夹 -->
          <span @click="enterFolder(file.name)" style="cursor: pointer; color: blue;">{{ file.name }} (- MB, {{
            file.formattedModTime }})</span>
          <n-button style="margin: 5px;" @click="downloadFile(file.name)">生成zip</n-button>
        </template>
        <template v-else>
          <!-- 文件显示 -->
          {{ file.name }} ({{ file.formattedSize }} MB, {{ file.formattedModTime }})
          <n-button style="margin: 5px;" @click="downloadFile(file.name)">下载</n-button>
        </template>
        <n-button style="margin: 5px;" @click="deleteFile(file.name)">删除</n-button>
        <n-popover trigger="click" placement="bottom-start">
          <template #trigger>
            <n-button style="margin: 5px;">修改文件名</n-button>
          </template>
          <div>
            <n-input :value="renameMap[file.name]" @update:value="(val) => renameMap[file.name] = val"
              placeholder="请输入新名称：" />
            <n-button style="margin: 5px;" @click="renameFile(file.name)">确定</n-button>
          </div>
        </n-popover>
      </li>
    </ul>
  </div>
</template>

<script lang="ts">
import { defineComponent, ref, onMounted, reactive } from 'vue'
import { NButton, NUpload, NInput, useMessage, NPopover } from 'naive-ui'
import axios from 'axios'

interface File {
  name: string
  size: number
  modTime: string
  isDir: boolean
  formattedModTime?: string
  formattedSize?: number
}

export default defineComponent({
  name: 'FilesView',
  components: {
    NButton,
    NUpload,
    NInput,
    NPopover
  },
  setup() {
    const files = ref<File[]>([])
    const folderName = ref<string>('')
    const message = useMessage()
    const currentPath = ref<string>('')
    const renameMap = reactive<Record<string, string>>({})

    const fetchFiles = async () => {
      try {
        const response = await axios.post('/api/files', { path: currentPath.value })
        console.log('Fetched files:', response.data) // 输出数据，检查是否正常，删除
        if (Array.isArray(response.data)) {
          files.value = response.data.map(file => {
            const formattedDate = new Date(file.modTime * 1000).toLocaleString()
            const formattedNumber = new Number((file.size / Math.pow(1024, 2)).toFixed(1))
            return {
              ...file,
              formattedModTime: formattedDate,
              formattedSize: formattedNumber
            }
          }) // 确保 response.data 是数组
        } else {
          files.value = [] // 如果数据格式不对，设置为空数组，避免错误
        }
      } catch (error) {
        console.error('Error fetching files:', error) // 打印错误信息
        message.error('文件加载失败')
      }
    }

    const enterFolder = (folderName: string) => {
      currentPath.value = currentPath.value ? `${currentPath.value}/${folderName}` : folderName
      fetchFiles()
    }

    const goBack = () => {
      if (!currentPath.value) return
      const parts = currentPath.value.split('/')
      parts.pop()
      currentPath.value = parts.join('/')
      fetchFiles()
    }

    // 在组件加载时自动执行 fetchFiles
    onMounted(() => {
      fetchFiles()
      console.log('正在获取文件...')
    })

    const handleUploadFinish = () => {
      fetchFiles()
      message.success('加载成功')
    }

    const downloadFile = async (name: string) => {
      try {
        const response = await axios.get(`/api/download?name=${name}`, { responseType: 'blob' })
        const url = window.URL.createObjectURL(new Blob([response.data]))
        const link = document.createElement('a')
        link.href = url
        link.setAttribute('download', name)
        document.body.appendChild(link)
        link.click()
        message.success('下载成功')
      } catch (error) {
        message.error('下载...')
      }
    }

    const deleteFile = async (name: string) => {
      try {
        await axios.post('/api/delete', { name })
        fetchFiles()
        message.success('删除成功')
      } catch (error) {
        message.error('删除失败')
      }
    }

    const renameFile = async (oldName: string) => {
      const newName = renameMap[oldName]
      if (!newName || newName.trim() === '') {
        message.warning('新名称不能为空')
        return
      }
      try {
        await axios.post('/api/rename', { oldName, newName: newName.trim() })
        fetchFiles()
        renameMap[oldName] = ''
        message.success('重命名成功')
      } catch (error) {
        message.error('重命名失败')
      }
    }

    const addFolder = async () => {
      const name = folderName.value
      const path = currentPath.value
      if (!name || name.trim() === '') {
        message.warning('文件夹名不能为空')
        return
      }
      try {
        await axios.post('/api/addFolder', { name: name.trim(), path: path })
        fetchFiles()
        folderName.value = ''
        message.success('文件夹添加成功')
      } catch (erro) {
        console.log(erro)
        message.error('文件夹添加失败')
      }
    }

    return {
      files,
      folderName,
      currentPath,
      renameMap,
      enterFolder,
      goBack,
      fetchFiles,
      handleUploadFinish,
      downloadFile,
      deleteFile,
      renameFile,
      addFolder

    }
  }
})
</script>

<style scoped></style>
